package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//事务工具类
public class DataSourceUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static  {
        Properties properties=new Properties();
        InputStream inputStream = DataSourceUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            inputStream.close();
            properties.load(inputStream);
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接失败");
        }
    }
    //阿里连接池
    public static DataSource getDataShurce(){
        return dataSource;
    }
    //当事务开启所需要重新配置连接
    public static Connection getConnection()  {
        Connection connection=threadLocal.get();
        try {
            if (connection==null){
                connection=dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    //关闭命令，结果集，接口
    public static void closeAll(Statement statement, ResultSet resultSet, Connection connection){
        try {
            if (statement!=null) {
                statement.close();
            }
            if (resultSet!=null){
                resultSet.close();
            }
            if (connection!=null){
                if (connection.getAutoCommit()){
                    connection.close();
                    threadLocal.remove();
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //事务开启
    public static void getAutoCommit() throws SQLException {
        Connection connection=getConnection();
        if (connection!=null){
            connection.setAutoCommit(false);
        }
    }
    //事务关闭
    public static void Commit() throws SQLException {
        Connection connection=getConnection();
        if (connection!=null){
            connection.commit();
        }
    }
    //事务回滚
    public  static void Rollback() throws SQLException {
        Connection connection=getConnection();
        if (connection!=null){
            connection.rollback();
        }
    }
    //事务退出
    public static  void  Closeone() throws SQLException {
        Connection connection=getConnection();
        if (connection!=null){
            connection.close();
            threadLocal.remove();
        }
    }
}
